package com.lin.mybatis.service;

import com.lin.mybatis.dao.UserDao;
import com.lin.mybatis.entity.User;
import org.apache.ibatis.cursor.Cursor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @作者: 林江
 * @创建时间: 2024/4/26
 * @功能: 对于5000条数据，各种批量操作。
 */
@Service
public class LimitPageService {

    @Autowired
    UserDao userDao;

    public void all() {
        long start = System.currentTimeMillis();
        userDao.selectList(null);
        System.out.println((System.currentTimeMillis() - start));

    }

    /**
     * 对50万的数据，按照每页1000条的数据进行分页，并记录每页所消耗的时间
     */
    public void page() throws InterruptedException {
        int pageNum = 0;
        int pageSize = 1000;
        long start = System.currentTimeMillis();
        List<User> list;
        do {
            list = userDao.page(pageNum * pageSize, pageSize);
            System.out.println("第" + (pageNum++) + "页,耗时：" + (System.currentTimeMillis() - start));
        } while (list.size() > 0);
    }

    /**
     * 主键优化
     */
    public void pageIdOptimize() throws InterruptedException {
        int pageNum = 0;
        int pageSize = 1000;
        long start = System.currentTimeMillis();
        List<User> list;
        do {
            list = userDao.pageIdOptimize(pageNum * pageSize, pageSize);
            System.out.println("第" + (pageNum++) + "页,耗时：" + (System.currentTimeMillis() - start));
        } while (list.size() > 0);
    }

    /**
     * 子查询优化
     */
    public void pageChildOptimize() throws InterruptedException {
        int pageNum = 0;
        int pageSize = 1000;
        long start = System.currentTimeMillis();
        List<User> list;
        do {
            list = userDao.pageChildOptimize(pageNum * pageSize, pageSize);
            System.out.println("第" + (pageNum++) + "页,耗时：" + (System.currentTimeMillis() - start));
        } while (list.size() > 0);
    }

    /**
     * 管道流一次性获取数据
     */
    @Transactional(rollbackFor = Exception.class)
    public void pagePipleOptimize() throws InterruptedException, IOException {
        int pageNum = 0;
        int pageSize = 1000;
        long start = System.currentTimeMillis();
        List<User> list;
        do {
            List<User> list1 = new ArrayList<>();
            Cursor<User> cursor = userDao.pagePipleOptimize(pageNum * pageSize, pageSize);
            for (User user : cursor) {
                list1.add(user);
            }
            // 取完了，就关闭
            if (cursor.isConsumed()) {
                cursor.close();
            }
            list = list1;
            System.out.println("第" + (++pageNum) + "页,耗时：" + (System.currentTimeMillis() - start));
        } while (list.size() > 0);
    }

}
